package xinyu.customer.home;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.KeyEvent;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.ittianyu.bottomnavigationviewex.BottomNavigationViewEx;
import com.logos.common.MainActivity;
import com.logos.common.base.BaseFragment;
import com.logos.tool.log.LogUtil;
import com.luck.picture.lib.tools.ToastManage;
import com.netease.nim.uikit.api.NimUIKit;
import com.netease.nim.uikit.common.ToastHelper;
import com.netease.nim.uikit.common.ui.drop.DropManager;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.NimIntent;
import com.netease.nimlib.sdk.Observer;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.auth.AuthServiceObserver;
import com.netease.nimlib.sdk.auth.LoginInfo;
import com.netease.nimlib.sdk.auth.constant.LoginSyncStatus;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.MsgServiceObserve;
import com.netease.nimlib.sdk.msg.SystemMessageObserver;
import com.netease.nimlib.sdk.msg.SystemMessageService;
import com.netease.nimlib.sdk.msg.model.CustomNotification;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.msg.model.RecentContact;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import xinyu.customer.JGApplication;
import xinyu.customer.R;
import xinyu.customer.base.AppBaseActivity;
import xinyu.customer.base.AppBaseFragment;
import xinyu.customer.base.BaseFragmentAdapter;
import xinyu.customer.chat.helper.CustomNotificationCache;
import xinyu.customer.chat.helper.SystemMessageUnreadManager;
import xinyu.customer.chat.reminder.ReminderItem;
import xinyu.customer.chat.reminder.ReminderManager;
import xinyu.customer.chat.session.SessionHelper;
import xinyu.customer.find.FindFragment;
import xinyu.customer.login.LoginActivity;
import xinyu.customer.login.LogoutHelper;
import xinyu.customer.main.MainFragment;
import xinyu.customer.mine.MineFragment;
import xinyu.customer.news.NewsFragment;
import xinyu.customer.util.Preferences;
import xinyu.customer.util.SpConstant;
import xinyu.customer.widget.CustomToastUtil;

/**
 * 主界面
 */
public class HomeActivity extends AppBaseActivity implements ReminderManager.UnreadNumChangedCallback{

    @BindView(R.id.bottom_navigation)
    BottomNavigationViewEx bottomNav;
    @BindView(R.id.vp)
    ViewPager vp;
    private List<Fragment> fragments;// used for ViewPager adapter
    private BaseFragmentAdapter adapter;

    private String TAG = HomeActivity.class.getSimpleName();
    private boolean isFirstIn;
    private boolean mIsExit;//再按一次退出用
    private static final String EXTRA_APP_QUIT = "APP_QUIT";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        ButterKnife.bind(this);

        isFirstIn = true;
        //不保留后台活动，从厂商推送进聊天页面，会无法退出聊天页面
        if (savedInstanceState == null && parseIntent()) {
            return;
        }
        initHome();
    }
    //首页初始化
    private void initHome() {
        initView();
        initData();
        loginNIM();
        registerMsgUnreadInfoObserver(true);
        registerSystemMessageObservers(true);
        registerCustomMessageObservers(true);
        requestSystemMessageUnreadCount();
        initUnreadCover();
    }



    private boolean parseIntent() {
        Intent intent = getIntent();
        if (intent.hasExtra(EXTRA_APP_QUIT)) {
            intent.removeExtra(EXTRA_APP_QUIT);
            onLogout();
            return true;
        }
        if (intent.hasExtra(NimIntent.EXTRA_NOTIFY_CONTENT)) {
            IMMessage message = (IMMessage) intent.getSerializableExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            intent.removeExtra(NimIntent.EXTRA_NOTIFY_CONTENT);
            switch (message.getSessionType()) {
                case P2P:
                    SessionHelper.startP2PSession(this, message.getSessionId(), null);
                    break;
                case Team:
                    SessionHelper.startTeamSession(this, message.getSessionId());
                    break;
            }

            return true;
        }

        return false;
    }

    private void initData() {
        fragments = new ArrayList<>();

        AppBaseFragment mainFragment = new MainFragment();
        AppBaseFragment findFragment = new FindFragment();
        AppBaseFragment newsFragment = new NewsFragment();
        AppBaseFragment mineFragment = new MineFragment();

        fragments.add(mainFragment);
        fragments.add(findFragment);
        fragments.add(newsFragment);
        fragments.add(mineFragment);

        adapter = new BaseFragmentAdapter(getSupportFragmentManager(), fragments);
        vp.setAdapter(adapter);
        vp.setOffscreenPageLimit(3);
        bottomNav.setupWithViewPager(vp);
    }

    private void initView() {
        bottomNav.enableAnimation(false);
        bottomNav.enableShiftingMode(false);
        bottomNav.enableItemShiftingMode(false);

        bottomNav.setTextSize(10);
        bottomNav.setIconSize(22, 22);
    }


    private void loginNIM() {
        final String account = SpConstant.getUserId();
        final String token = getString(R.string.nim_app_id);
        NimUIKit.login(new LoginInfo(account, token), new RequestCallback<LoginInfo>() {
            @Override
            public void onSuccess(LoginInfo info) {
                JGApplication.setLoginInfo(info);
                LogUtil.debug(TAG, "nim login onSuccess:>>" + info.getAccount());
                NimUIKit.loginSuccess(account);
                saveLoginInfo(account, token);
            }

            @Override
            public void onFailed(int code) {
                LogUtil.debug(TAG, "nim login failed:>>" + code);
            }

            @Override
            public void onException(Throwable exception) {
                LogUtil.debug(TAG, "LoginInfo code:" + exception.getMessage());
            }
        });

    }

    private void saveLoginInfo(String account, String token) {
        Preferences.saveUserAccount(account);
        Preferences.saveUserToken(token);
    }

    private void onLogout() {
        Preferences.saveUserToken("");
        // 清理缓存&注销监听
        LogoutHelper.logout();
        // 启动登录
        startActivity(new Intent(HomeActivity.this,LoginActivity.class));
        finish();
    }
    @Override
    protected void onNewIntent(Intent intent) {
        setIntent(intent);
        parseIntent();
    }

    @Override
    public void onResume() {
        super.onResume();
        // 第一次 ， 三方通知唤起进会话页面之类的，不会走初始化过程
        boolean temp = isFirstIn;
        isFirstIn = false;
        if (temp) {
            return;
        }
        //如果不是第一次进 ， eg: 其他页面back
        if (vp == null) {
            initHome();
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.clear();
    }


    /**
     * 注册未读消息数量观察者
     */
    private void registerMsgUnreadInfoObserver(boolean register) {
        if (register) {
            ReminderManager.getInstance().registerUnreadNumChangedCallback(this);
        } else {
            ReminderManager.getInstance().unregisterUnreadNumChangedCallback(this);
        }
    }

    // TODO 未读消息数量观察者实现
    @Override
    public void onUnreadNumChanged(ReminderItem item) {
//        MainTab tab = MainTab.fromReminderId(item.getId());
//        if (tab != null) {
//            tabs.updateTab(tab.tabIndex, item);
//        }
    }

    /**
     * 注册/注销系统消息未读数变化
     */
    private void registerSystemMessageObservers(boolean register) {
        NIMClient.getService(SystemMessageObserver.class).observeUnreadCountChange(
                sysMsgUnreadCountChangedObserver, register);
    }
    private Observer<Integer> sysMsgUnreadCountChangedObserver = (Observer<Integer>) unreadCount -> {
        SystemMessageUnreadManager.getInstance().setSysMsgUnreadCount(unreadCount);
        ReminderManager.getInstance().updateContactUnreadNum(unreadCount);
    };

    private void registerCustomMessageObservers(boolean register) {
        NIMClient.getService(MsgServiceObserve.class).observeCustomNotification(
                customNotificationObserver, register);
    }

    // sample
    Observer<CustomNotification> customNotificationObserver = (Observer<CustomNotification>) notification -> {
        // 处理自定义通知消息
        LogUtil.debug("demo", "receive custom notification: " + notification.getContent() + " from :" +
                notification.getSessionId() + "/" + notification.getSessionType() +
                "unread=" + notification.getConfig().enableUnreadCount + " " + "push=" +
                notification.getConfig().enablePush + " nick=" +
                notification.getConfig().enablePushNick);
        try {
            JSONObject obj = JSONObject.parseObject(notification.getContent());
            if (obj != null && obj.getIntValue("id") == 2) {
                // 加入缓存中
                CustomNotificationCache.getInstance().addCustomNotification(notification);
                // Toast
                String content = obj.getString("content");
                String tip = String.format("自定义消息[%s]：%s", notification.getFromAccount(), content);
            }
        } catch (JSONException e) {
            LogUtil.debug("demo", e.getMessage());
        }
    };

    /**
     * 查询系统消息未读数
     */
    private void requestSystemMessageUnreadCount() {
        int unread = NIMClient.getService(SystemMessageService.class)
                .querySystemMessageUnreadCountBlock();
        SystemMessageUnreadManager.getInstance().setSysMsgUnreadCount(unread);
        ReminderManager.getInstance().updateContactUnreadNum(unread);
    }

    //初始化未读红点动画
    private void initUnreadCover() {
        DropManager.getInstance().init(this, findView(R.id.unread_cover), (id, explosive) -> {
            if (id == null || !explosive) {
                return;
            }
            if (id instanceof RecentContact) {
                RecentContact r = (RecentContact) id;
                NIMClient.getService(MsgService.class).clearUnreadCount(r.getContactId(),
                        r.getSessionType());
                return;
            }
            if (id instanceof String) {
                if (((String) id).contentEquals("0")) {
                    NIMClient.getService(MsgService.class).clearAllUnreadCount();
                } else if (((String) id).contentEquals("1")) {
                    NIMClient.getService(SystemMessageService.class)
                            .resetSystemMessageUnreadCount();
                }
            }
        });
    }
}
